package com.wannengbang.cloudleader.mine;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.RecyclerView;

import com.ethanhua.skeleton.Skeleton;
import com.ethanhua.skeleton.SkeletonScreen;
import com.google.gson.Gson;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.wannengbang.cloudleader.R;
import com.wannengbang.cloudleader.base.BaseActivity;
import com.wannengbang.cloudleader.base.DataCallBack;
import com.wannengbang.cloudleader.bean.BaseResponseBean;
import com.wannengbang.cloudleader.bean.NumberBean;
import com.wannengbang.cloudleader.bean.OrderDetailsBean;
import com.wannengbang.cloudleader.bean.OrderListBean;
import com.wannengbang.cloudleader.bean.PrepareConfigBean;
import com.wannengbang.cloudleader.bean.UserInfoBean;
import com.wannengbang.cloudleader.event.OrderRefushEvent;
import com.wannengbang.cloudleader.homepage.QRActivity;
import com.wannengbang.cloudleader.homepage.model.HomePageModelImpl;
import com.wannengbang.cloudleader.homepage.model.IHomePageModel;
import com.wannengbang.cloudleader.mine.adapter.ReConfigListAdapter;
import com.wannengbang.cloudleader.mine.model.IMineModel;
import com.wannengbang.cloudleader.mine.model.MineModelImpl;
import com.wannengbang.cloudleader.utils.NumberFormatUtils;
import com.wannengbang.cloudleader.utils.SPManager;
import com.wannengbang.cloudleader.utils.ToastUtil;
import com.wannengbang.cloudleader.widget.AppTitleBar;
import com.wannengbang.cloudleader.widget.ViewLoading;
import com.wannengbang.cloudleader.widget.WrapContentLinearLayoutManager;

import org.greenrobot.eventbus.EventBus;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PrepareGoodsActivity extends BaseActivity {
    @BindView(R.id.title_bar)
    AppTitleBar titleBar;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.tv_add_project)
    TextView tvAddProject;
    @BindView(R.id.tv_commit)
    TextView tvCommit;
    @BindView(R.id.tv_num1)
    TextView tvNum1;
    @BindView(R.id.tv_num2)
    TextView tvNum2;
    @BindView(R.id.tv_num3)
    TextView tvNum3;
    private IHomePageModel homePageModel;
    private ReConfigListAdapter listAdapter;
    private List<PrepareConfigBean.DataBean> beanList;
    private SkeletonScreen skeletonScreen;
    private String shop_order_id;
    private String select_type;
    private IMineModel mineModel;
    private OrderListBean.DataBean.ItemListBean dataBean;
    private PrepareConfigBean.DataBean configBean;
    private int scanType;
    private UserInfoBean userInfoBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_prepare_goods);
        ButterKnife.bind(this);
        initData();
    }

    public void initData() {
        userInfoBean = new Gson().fromJson(SPManager.getInstance().getUserInfoJson(), UserInfoBean.class);
        mineModel = new MineModelImpl();
        shop_order_id = getIntent().getStringExtra("shop_order_id");
        select_type = getIntent().getStringExtra("select_type");
        homePageModel = new HomePageModelImpl();
        beanList = new ArrayList<>();
        listAdapter = new ReConfigListAdapter(beanList);
        recyclerView.setLayoutManager(new WrapContentLinearLayoutManager(mActivity));
        recyclerView.setAdapter(listAdapter);
        listAdapter.setOnCallBackListener((type, position) -> {
            configBean = beanList.get(position);
            int goods_count = 0;
            if (type == 1) {
                beanList.remove(position);
                listAdapter.notifyDataSetChanged();
                if (beanList.size() == 0) {
                    tvNum2.setText("已输入配货数量：" + 0);
                }
            }
            if (type == 2) {
                for (PrepareConfigBean.DataBean bean : beanList) {
                    if (!TextUtils.isEmpty(bean.getStart_no()) && !TextUtils.isEmpty(bean.getEnd_no())) {

                        if (NumberFormatUtils.isNumeric(bean.getStart_no()) && NumberFormatUtils.isNumeric(bean.getEnd_no())) {
                            BigInteger d_start = new BigInteger(bean.getStart_no());
                            BigInteger d_end = new BigInteger(bean.getEnd_no());
                            BigInteger value = d_end.subtract(d_start);
                            goods_count = (int) (goods_count + 1 + (value.longValue()));
                        } else {
                            String min = bean.getStart_no().replaceAll("[a-zA-Z]", "");
                            String max = bean.getEnd_no().replaceAll("[a-zA-Z]", "");
                            BigInteger d_start = new BigInteger(min);
                            BigInteger d_end = new BigInteger(max);
                            BigInteger value = d_end.subtract(d_start);
                            goods_count = (int) (goods_count + 1 + (value.longValue()));
                        }

                    }
                }
                tvNum2.setText("已输入配货数量：" + goods_count);
//                requestCountPrepareNo();
            }
            //开始码
            if (type == 3) {
                scanType = 3;
                IntentIntegrator integrator = new IntentIntegrator(mActivity);
                integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
                integrator.setOrientationLocked(false);
                integrator.setCaptureActivity(QRActivity.class);
                integrator.initiateScan();
            }
            //结束码
            if (type == 4) {
                scanType = 4;
                IntentIntegrator integrator = new IntentIntegrator(mActivity);
                integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
                integrator.setOrientationLocked(false);
                integrator.setCaptureActivity(QRActivity.class);
                integrator.initiateScan();
            }
        });

        skeletonScreen = Skeleton.bind(recyclerView)
                .adapter(listAdapter)
                .color(R.color.shimmer_color_2)
                .shimmer(true)
                .angle(20)
                .frozen(false)
                .duration(1000)
                .count(20)
                .load(R.layout.item_skeleton_income_list)
                .show();

        requestOrderShow();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //扫描结果回调
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {
            if (result.getContents() == null) {
                Toast.makeText(this, "扫描取消", Toast.LENGTH_LONG).show();
            } else {
                IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
                String code = scanResult.getContents();
                if (scanType == 3 && configBean != null) {
                    if (!TextUtils.isEmpty(code) && code.length() > 2 && "sn".equals(code.substring(0, 2))) {
                        configBean.setStart_no(code.substring(2));
                    } else {
                        configBean.setStart_no(code);
                    }
                    listAdapter.notifyDataSetChanged();
                }
                if (scanType == 4 && configBean != null) {
                    if (!TextUtils.isEmpty(code) && code.length() > 2 && "sn".equals(code.substring(0, 2))) {
                        configBean.setEnd_no(code.substring(2));
                    } else {
                        configBean.setEnd_no(code);
                    }
                    listAdapter.notifyDataSetChanged();
                }
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    /**
     * 计算发货数量
     */
    public void requestCountPrepareNo() {
        if (beanList.size() == 1) {
            if (TextUtils.isEmpty(beanList.get(0).getStart_no()) || TextUtils.isEmpty(beanList.get(0).getEnd_no())) {
                return;
            }
        }
        homePageModel.requestCountPrepareNo(beanList, new DataCallBack<NumberBean>() {
            @Override
            public void onSuccessful(NumberBean bean) {
                tvNum2.setText("已输入配货数量：" + bean.getData());
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    public void requestOrderShow() {
        ViewLoading.showProgress(mActivity);
        mineModel.requestOrderShow(shop_order_id, select_type, new DataCallBack<OrderDetailsBean>() {
            @Override
            public void onSuccessful(OrderDetailsBean bean) {
                dataBean = bean.getData();
                if (dataBean != null) {
                    beanList.clear();
                    //总账户 订单状态 待收货 已完成
                    if (userInfoBean.getData().getId() == 1 && (dataBean.getOrder_status() == 3 || dataBean.getOrder_status() == 4)) {
                        int goods_count = 0;
                        if (dataBean.getDevice_group() != null && dataBean.getDevice_group().size() > 0) {
                            for (PrepareConfigBean.DataBean dataBeans : dataBean.getDevice_group()) {
                                if (!TextUtils.isEmpty(dataBeans.getStart_no()) && !TextUtils.isEmpty(dataBeans.getEnd_no())) {

                                    if (NumberFormatUtils.isNumeric(dataBeans.getStart_no()) && NumberFormatUtils.isNumeric(dataBeans.getEnd_no())) {
                                        BigInteger d_start = new BigInteger(dataBeans.getStart_no());
                                        BigInteger d_end = new BigInteger(dataBeans.getEnd_no());
                                        BigInteger value = d_end.subtract(d_start);
                                        goods_count = (int) (goods_count + 1 + (value.longValue()));
                                    } else {
                                        String min = dataBeans.getStart_no().replaceAll("[a-zA-Z]", "");
                                        String max = dataBeans.getEnd_no().replaceAll("[a-zA-Z]", "");
                                        BigInteger d_start = new BigInteger(min);
                                        BigInteger d_end = new BigInteger(max);
                                        BigInteger value = d_end.subtract(d_start);
                                        goods_count = (int) (goods_count + 1 + (value.longValue()));
                                    }
                                }
                            }
                        }
                        tvNum3.setText("已配货数量：" + goods_count);
                        tvNum3.setVisibility(View.VISIBLE);
                        beanList.add(new PrepareConfigBean.DataBean());
                    } else {
                        if (dataBean.getDevice_group() != null && dataBean.getDevice_group().size() > 0) {
                            beanList.addAll(dataBean.getDevice_group());
                        } else {
                            beanList.add(new PrepareConfigBean.DataBean());
                        }
                    }

                    listAdapter.notifyDataSetChanged();
                    skeletonScreen.hide();

                    tvNum1.setText("需要配货总数量：" + dataBean.getShop_goods_count());
                }
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }


    @OnClick({R.id.tv_add_project, R.id.tv_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_add_project:
                beanList.add(new PrepareConfigBean.DataBean());
                listAdapter.notifyDataSetChanged();
                break;
            case R.id.tv_commit:
                if (beanList.size() == 0) {
                    ToastUtil.showShort("请添加配置");
                    return;
                }
                List<PrepareConfigBean.DataBean> dataBeanList = new ArrayList<>();
                for (PrepareConfigBean.DataBean dataBean : beanList) {

                    PrepareConfigBean.DataBean bean = new PrepareConfigBean.DataBean();
                    if (!TextUtils.isEmpty(dataBean.getStart_no())) {
                        bean.setStart_no(dataBean.getStart_no());
                    }
                    if (!TextUtils.isEmpty(dataBean.getEnd_no())) {
                        bean.setEnd_no(dataBean.getEnd_no());
                    }
                    dataBeanList.add(bean);
                }
                requestStoreSaveRechargeConfig(dataBeanList);
                break;
        }
    }

    public void requestStoreSaveRechargeConfig(List<PrepareConfigBean.DataBean> beanList) {
        ViewLoading.showProgress(mActivity, "保存中......");
        homePageModel.requesPrepareGoodsConfig(shop_order_id, 0, beanList, new DataCallBack<BaseResponseBean>() {
            @Override
            public void onSuccessful(BaseResponseBean bean) {
                ToastUtil.showShort("保存成功");
                EventBus.getDefault().post(new OrderRefushEvent());
                finish();
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }
}
